package com.example.yilanchatserver.business.freechat.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.example.yilanchatserver.application.controller.vo.ErnieBotTokenRespVO;
import com.example.yilanchatserver.business.freechat.BusinessErrorCodes;
import com.example.yilanchatserver.business.freechat.BusinessException;
import com.example.yilanchatserver.business.freechat.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 文心一言工具类
 *
 * @author ziyu
 * @date 2023/9/5
 */
public class ErnieBotUtils {

    /**
     * 获取accessToken
     *
     * @param accessTokenUrl
     * @param apiKey
     * @param secretKey
     * @return
     */
    public static String getAccessToken(String accessTokenUrl, String apiKey, String secretKey) throws Exception {
        String accessToken = "";
        StringBuilder reqUrl = new StringBuilder();
        reqUrl.append(accessTokenUrl).append("?grant_type=client_credentials").append("&client_id=").append(apiKey).append("&client_secret=").append(secretKey);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");

        String response = HttpUtil.createPost(reqUrl.toString()).addHeaders(headers).execute().body();
        ErnieBotTokenRespVO respVO = JSON.parseObject(response, ErnieBotTokenRespVO.class);
        String error = respVO.getError();
        if (StringUtils.isEmpty(error)) {
            accessToken = respVO.getAccessToken();
        } else {
            throw new BusinessException(BusinessErrorCodes.DEFAULT_BUSINESS_ERROR);
        }
        return accessToken;
    }
}
